import json

from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
import redis
import datetime
from django.core.cache import cache

user_list = []

conn = redis.Redis(decode_responses=True)

user_mesg_list = []


# cache.set('tody_time','')
class ChatConsumer(WebsocketConsumer):
    def _mesg_redis(self):
        pass

    def websocket_connect(self, message):
        # 客户端建立链接时,自动触发

        print('请求链接')
        self.accept()  # 建立链接,并自动帮你维护每一个客户端
        if self in user_list:
            return
        user_list.append(self)
        # self.websocket_receive(message=None,newuser=self)

    def websocket_receive(self, message, newuser=None):
        tody_time = ''
        # if newuser:
        #     for mesg in user_mesg:
        #         newuser.send(mesg)
        #     return
        # 获取消息
        message = message.get('text')
        message_obj = json.loads(message)
        print(message_obj)
        # 获取当前时间
        now_time = datetime.datetime.today().date()
        # 获取 存储的时间
        tody_time = cache.get('tody_time')

        if now_time != tody_time:
            tody_time = now_time
            # 存入时间
            cache.set('tody_time', tody_time)

            user_mesg = f'{tody_time}_mesg'
            conn.rpush(user_mesg, message)
            global user_mesg_list
            user_mesg_list = []
            user_mesg_list.append(message)
            conn.expire(user_mesg, 2626560)
        conn.rpush(f'{tody_time}_mesg', message)
        user_mesg_list.append(message)
        print(user_mesg_list)
        # 客户端发送数据过来 自动触发
        for i in user_list:
            i.send(text_data=message)
            print(message)

    def websocket_disconnect(self, message):
        # 客户端 断开连接时自动触发
        print(f'{self}断开链接')
        user_list.remove(self)
        raise StopConsumer
        pass
